package me.goldze.mvvmhabit.utils;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;


import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by Stefan on 2020/7/7$
 */
public class QRImageUtils {


    //保存在本地并一键分享
    public static String sharePic(Context context, Bitmap cachebmp/*, String filename*/) {
        final File qrImage = new File(Environment.getExternalStorageDirectory(), System.currentTimeMillis() + "");
        try {
            if (qrImage.exists()) {
                qrImage.delete();
            }
            qrImage.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        FileOutputStream fOut = null;
        try {
            fOut = new FileOutputStream(qrImage);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        if (cachebmp == null) {
            return "";
        }
        try {
            cachebmp.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
            fOut.flush();
            fOut.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        MediaStore.Images.Media.insertImage(context.getContentResolver(), cachebmp, /*filename*/qrImage.getName(), null);
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri uri = Uri.fromFile(qrImage);
        intent.setData(uri);
        context.sendBroadcast(intent);
        return qrImage.getPath();
    }
}
